package com.axend.aerosense.room.ui.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.room.BR;
import com.axend.aerosense.room.entity.RoomUnassignedDevicesBean;
import com.axend.aerosense.room.entity.RoomsGetResult;
import com.axend.aerosense.room.ui.activity.RoomAddActivity;
import com.axend.aerosense.room.ui.activity.RoomDetailsActivity;
import com.axend.aerosense.room.ui.activity.RoomDeviceListActivity;
import com.axend.aerosense.room.ui.activity.RoomEditActivity;
import com.axend.aerosense.room.ui.activity.RoomSceneLearnActivity;
import com.axend.aerosense.room.ui.adapter.RoomDeviceListAdapter;
import com.axend.aerosense.room.ui.adapter.RoomListAdapter;
import com.axend.aerosense.room.viewmodel.RoomViewModel;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gyf.immersionbar.ImmersionBar;
import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.impl.ILoginStatusChanged;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.base.utils.DisplayUtils;
import com.axend.aerosense.base.viewmodel.BaseViewModelFactroy;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterFragmentPath;
import com.axend.aerosense.room.R;
import com.axend.aerosense.room.databinding.RoomFragmentBinding;
import com.axend.aerosense.room.entity.RoomItemBean;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ChenHongWei
 * @date :2020/12/18 11:07
 */
@Route(path = RouterFragmentPath.Room.PAGE_MAIN_ROOM)
public class RoomFragment extends MvvmBaseFragment<RoomFragmentBinding, RoomViewModel>
        implements ILoginStatusChanged, ILoadDataResult<RoomsGetResult> {
    private boolean isImmersionBarTransparent = true; // 第一次可见
    private List<RoomItemBean> roomList = new ArrayList<>();
    private RoomListAdapter adapter;
    private boolean isFirstDisaple = true;
    private ArrayList<RoomItemBean> roomInfo = new ArrayList<RoomItemBean>();
    private boolean isCreatView = false;
    private RoomUnassignedDevicesBean unassignedDevicesInfo;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ((AppCompatActivity) getActivity()).setSupportActionBar(viewDataBinding.roomToolbar);
        isFirstDisaple = false;
        init();
    }

    private void init(){
        adapter = new RoomListAdapter();
        //item点击监听
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                RoomItemBean bean = (RoomItemBean) adapter.getData().get(position);
                Intent intent = new Intent(getActivity(), RoomAddActivity.class);
                intent.putExtra(RoomSettingFragment.OPEN_PARAM_ROOMINFO, bean);
                startActivity(intent);
            }
        });
        viewDataBinding.roomRoomList.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter.setList(roomList);
        viewDataBinding.roomRoomList.setAdapter(adapter);
        viewDataBinding.roomRoomList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect,
                                       View view,
                                       RecyclerView parent,
                                       RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = DisplayUtils.dip2px(8);
            }
        });

        viewDataBinding.roomNestedScrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            Rect scrollBounds = new Rect();
            View firstVisibItem = viewDataBinding.roomRoomList.getChildAt(0);
            firstVisibItem.getGlobalVisibleRect (scrollBounds);

            Rect rect = new Rect();
            viewDataBinding.roomToolbar.getGlobalVisibleRect (rect);

            if (scrollBounds.top > rect.bottom) {//可见
                viewDataBinding.roomToolbar.setBackgroundResource(android.R.color.transparent);
//                viewDataBinding.roomTvRoomName.setTextColor(getResources().getColor(R.color.white));
//                viewDataBinding.roomIvAdd.setImageResource(R.drawable.common_user_icon_add);
//                isImmersionBarTransparent = true;
            }else {//完全不可见
                viewDataBinding.roomToolbar.setBackgroundResource(R.color.common_setting_item_bg);
//                viewDataBinding.roomTvRoomName.setTextColor(getResources().getColor(R.color.black));
//                viewDataBinding.roomIvAdd.setImageResource(R.drawable.common_user_icon_add2);
//                isImmersionBarTransparent = false;
            }
//            setImmersionBar();

        });

        viewDataBinding.roomTvRoomName.setTextColor(getResources().getColor(R.color.black));
        viewDataBinding.roomIvAdd.setImageResource(R.drawable.common_user_icon_add2);

        viewDataBinding.roomIvAdd.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), RoomAddActivity.class);
//            Intent intent = new Intent(getActivity(), RoomSceneLearnActivity.class);
            startActivity(intent);
        });
        viewDataBinding.roomEmptyView.setVisibility(View.GONE);

        viewDataBinding.roomEmptyView.setOnClickListener(v->{
            Intent intent = new Intent(getActivity(), RoomAddActivity.class);
            startActivity(intent);
        });

        viewDataBinding.roomRefreshLayout.setOnRefreshListener(v->{
            if(null != viewModel){
                viewModel.onLoad();
            }
        });

        //编辑按钮
        viewDataBinding.roomEdit.setOnClickListener(v -> {
            startActivity(new Intent(getActivity(), RoomEditActivity.class));
        });

        viewDataBinding.roomUnassignedDevice.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), RoomDeviceListActivity.class);
            intent.putExtra(RoomDeviceListActivity.PAGER_FLAG, RoomDeviceListActivity.UNASSIGNED_DEVICES_LIST_PAGER);
            if (unassignedDevicesInfo != null){
                intent.putExtra(RoomDeviceListActivity.ROOM_UUID, unassignedDevicesInfo.getRoomUuid());
            }
            startActivity(intent);
        });

        viewDataBinding.roomRefreshLayout.setNoMoreData(true);
        viewDataBinding.roomRefreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        setLoadSir(viewDataBinding.roomRefreshLayout);
        showLoading();
        viewModel.onLoad();
        LiveDatabus.getInstance().with(Gobal.EVENT_KEY.REFESH_ROOM ,Integer.class)
                .observe(getViewLifecycleOwner(), bean-> {
                    // 信息变更时重新刷新
                    viewModel.onLoad();
                });
        isCreatView = true;
    }

    /**
     * 已滑动的距离
     */
    private int getDistance(){
        LinearLayoutManager layoutManager = (LinearLayoutManager) viewDataBinding.roomRoomList.getLayoutManager();
        View firstVisibItem = viewDataBinding.roomRoomList.getChildAt(0);
        int firstItemPosition = layoutManager.findFirstVisibleItemPosition();
        int itemCount = layoutManager.getItemCount();
        int recycleViewHeight = viewDataBinding.roomRoomList.getHeight();
        int itemHeight = firstVisibItem.getHeight();
        int firstItemBottom = layoutManager.getDecoratedBottom(firstVisibItem);
        return (firstItemPosition + 1)*itemHeight - firstItemBottom;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);
    }

    public void setImmersionBar() {
        ImmersionBar.with(this)
                .statusBarColor(R.color.common_setting_item_bg)
                .fitsSystemWindows(true)
                .statusBarDarkFont(true)
                .autoDarkModeEnable(true).init();
//        if(isImmersionBarTransparent) {
//            ImmersionBar.with(this)
//                    .statusBarColor(R.color.common_setting_item_bg)
//                    .fitsSystemWindows(true)
//                    .statusBarDarkFont(true)
//                    .autoDarkModeEnable(true).init();
//        }else{
//            ImmersionBar.with(RoomFragment.this)
//                    .statusBarColor(android.R.color.white)
//                    .fitsSystemWindows(true)
//                    .statusBarDarkFont(true)
//                    .autoDarkModeEnable(true).init();
//        }
    }

    @Override
    public void onResume() {
        super.onResume();
        setImmersionBar();
        if(!isFirstDisaple){
//            viewModel.onLoad();
        }
    }

    @Override
    public void onPause() {
//        ImmersionBar.destroy(this);
//        ImmersionBar.with(this)
//                .statusBarColor(android.R.color.transparent)
//                .navigationBarColor(android.R.color.transparent)
//                .fitsSystemWindows(true)
//                .autoDarkModeEnable(true)
//                .init();
        super.onPause();
    }

    @Override
    public int getLayoutId() {
        return R.layout.room_fragment;
    }

    @Override
    public int getBindingVariable() {
        return BR.data;
    }

    @Override
    protected RoomViewModel getViewModel() {
        BaseViewModelFactroy<RoomsGetResult> myViewModelFactroy = new BaseViewModelFactroy<>(this, this);
        return new ViewModelProvider(this, myViewModelFactroy).get(RoomViewModel.class);
    }

    @Override
    protected void onRetryBtnClick() {
        showLoading();
        viewModel.onLoad();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void loginStatusChanged() {
        if(isCreatView){
            getViewModel().isRefresh = false;
            onRetryBtnClick();
        }
    }

    @Override
    public void loadDataSuccess(RoomsGetResult roomsGetResult) {
        viewDataBinding.roomRefreshLayout.finishRefresh();
        roomInfo.clear();
        if(null != roomsGetResult){
            roomInfo.addAll(roomsGetResult.getRoomInfo());
        }
        adapter.setList(roomInfo);

        int deviceCount = 0;
        if (roomsGetResult.getUnassignedDevicesInfoList() != null && roomsGetResult.getUnassignedDevicesInfoList().size() > 0){
            unassignedDevicesInfo = roomsGetResult.getUnassignedDevicesInfoList().get(0);
            deviceCount = unassignedDevicesInfo.getRadarCount();

        }
        setTopUnassignedTips(deviceCount);

        if(null != roomsGetResult && null != roomsGetResult.getRoomInfo() && roomsGetResult.getRoomInfo().size()>0){
            viewDataBinding.roomEmptyView.setVisibility(View.GONE);
            viewDataBinding.roomBottomView.setVisibility(View.VISIBLE);
            viewDataBinding.roomRoomList.setVisibility(View.VISIBLE);
            viewDataBinding.roomEdit.setVisibility(View.VISIBLE);
        }else{
            viewDataBinding.roomEmptyView.setVisibility(View.VISIBLE);
            viewDataBinding.roomRoomList.setVisibility(View.GONE);
            viewDataBinding.roomEdit.setVisibility(View.GONE);
            viewDataBinding.roomBottomView.setVisibility(View.GONE);
        }

    }

    @Override
    public void loadDataFail(String decs) {
        viewDataBinding.roomRefreshLayout.finishRefresh();
    }

    private void setTopUnassignedTips(int radarCount){
        viewDataBinding.roomUnassignedDevice.setVisibility(radarCount > 0 ? View.VISIBLE : View.GONE);
        if (radarCount > 0){
            viewDataBinding.roomTvUnassignedTitle
                    .setText(String.format(getString(R.string.room_unassigned_devices_title), String.valueOf(radarCount)));
        }
    }
}
